#!/usr/bin/env python3
#-*- coding: utf-8 -*-
#要编写一个ORM框架，所有的类都只能动态定义，因为只有使用者才能根据表的结构定义出对应的类来

class Field:
	def __init__(self, value, columnType):
		self.value = value
		self.columnType = columnType

	def __str__(self):
		return "got field %s <== type of %s" % (self.value, self.columnType)

class StringField(Field):
	def __init__(self, value):
		#notice how to call init method of super class.
		super(StringField, self).__init__(value, "String")

class IntegerField(Field):
	def __init__(self, value):
		super(IntegerField, self).__init__(value, "Ingeger")

class ModelMetaClass(type):
	def __new__(cls, name, bases, attrs):
		if name == 'Model':
			return type.__new__(cls, name, bases, attrs)
		print('Found model %s~~' % name)

class Model:
	def __init__(self, **kw):
		super(Model, self).__init__(**kw)

	def __getattr__(self, key):
		try:
			return self[key]
		except KeyError:
			raise AttrbuteError("'Model' does not have the attrbute '%s'" % key)

	def __setattr__(self, key, value):
		self.key = value

	def save(self):
		fields = []
		params = []
		args = []
		for k, v in self.__mapping__.items():
			fields.append(v.name)
			params.append("?")
			args.append(getattr(self, k, None))
		sql = "insert into %s (%s) values (%s)" % (self.__table__, ','.join(fields), ','.join(args))
		print("Sql: %s" % sql)
		print("Args: %s" % str(args))

class User(Model, metaclass=ModelMetaClass):
	id = IntegerField('id')
    name = StringField('name')

#by adding this, we can execute the module in order to test it.
if __name__ == '__main__':
	i = IntegerField(1)
	u = User(id=123, name='wowo')
